<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="定时发送播报" name="first">
          <h1 class="title">定时发送播报</h1>
          <!-- 新增 -->
          <el-button type="success" @click="sipSend">播放计划</el-button>
           <el-button type="success" @click="exportToExcel">导出</el-button>
          <!-- 定时填写模块 -->

          <el-table :data="sipTable" border style="width: 100%">
            <el-table-column prop="call_name" label="接收地" width="120">
              <template slot-scope="props">
                <el-popover
                  placement="top-start"
                  title="接收地"
                  width="200"
                  trigger="hover"
                  :content="props.row.call_name"
                >
                  <div slot="reference">
                    {{ props.row.call_name.slice(0, 20) }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="播报内容">
              <template slot-scope="props">
                <el-popover
                  placement="top-start"
                  title="播报内容"
                  width="200"
                  trigger="hover"
                  :content="props.row.content"
                >
                  <div slot="reference">
                    {{ props.row.content.slice(0, 20) }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column label="开始时间" width="140">
              <template slot-scope="scope">
                {{
                  $moment(scope.row.start_time * 1000).format(
                    "YYYY-MM-DD/HH:mm"
                  )
                }}
              </template>
            </el-table-column>

              <el-table-column label="结束时间" width="140">
              <template slot-scope="scope">
                {{
                  $moment(scope.row.end_time_date * 1000).format(
                    "YYYY-MM-DD/HH:mm"
                  )
                }}
              </template>
            </el-table-column>

            <!-- <el-table-column label="结束时间" width="140">
              <template slot-scope="scope">
                {{
                  scope.row.days !== 1
                    ? "0"
                    : $moment(scope.row.start_time_date * 1000).format(
                        "YYYY-MM-DD/HH:mm"
                      )
                }}
              </template>
            </el-table-column> -->

            <!-- <el-table-column label="播报间隔" width="120">
          <template slot-scope="scope">
            {{ scope.row.broadcast_interval + "秒" }}
          </template>
        </el-table-column> -->

            <!-- <el-table-column prop="broadcast_mode" label="播报模式" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.broadcast_mode === 1">单次</span>
            <span v-if="scope.row.broadcast_mode === 2">循环</span>
            <span v-if="scope.row.broadcast_mode === 3">永久</span>
          </template>
        </el-table-column> -->
            <el-table-column prop="" label="广播模式" width="120">
              <template slot-scope="scope">
                <span>
                  {{
                    scope.row.days === 0
                      ? "某天播放"
                      : scope.row.days === 1
                      ? "限时播放"
                      : scope.row.days === 2
                      ? "每天播放"
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="播报次数" width="120">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.times }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="播报间隔" width="120">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.interval / 60 + "分钟" }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="广播状态" width="120">
              <template slot-scope="scope">
                <span
                  class="el-icon-success"
                  style="color: #13ce66"
                  v-if="scope.row.status === 0"
                ></span>
                <span
                  class="el-icon-warning"
                  style="color: #fbdc3c"
                  v-if="scope.row.status === 1"
                ></span>
                <span
                  class="el-icon-circle-close"
                  style="color: #ff4949"
                  v-if="scope.row.status === 2"
                ></span>
                <span>
                  {{
                    scope.row.status === 0
                      ? "未播放"
                      : scope.row.status === 1
                      ? "已播放"
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作">
              <template slot-scope="scope">
                <!-- <el-button @click="sendDialog(scope.row)" size="mini"
              >发送</el-button
            > -->
                <!-- <el-button @click="sipStop(scope.row)" size="mini">{{
                  scope.row.stop === 0 ? "停止" : "启动"
                }}</el-button> -->
                <!-- <el-button @click="edit(scope.row)" size="mini">编辑</el-button> -->
                <el-button @click="del(scope.row)" size="mini" type="danger"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            layout="prev, pager, next"
            :page-count="paging.total"
            @current-change="page_change"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="定时播放"
      :visible.sync="CycleAndSenddialogVisible"
      width="70%"
      @open="sipOpen"
      :before-close="close"
    >
      <div class="dashboard-container">
        <!-- <div class="dashboard-text">name: {{ name }}</div> -->
        <el-card class="box-card">
          <!-- 表单 -->
          <div class="timeBox">
            <el-form
              v-loading="loading"
              ref="form"
              :model="form"
              :rules="Rules"
              label-width="170px"
            >
              <!-- 播报模式 -->
              <!-- <el-form-item label="播报模式" prop="broadcast_mode">
                <el-select
                  v-model="form.broadcast_mode"
                  placeholder="请选择播报模式"
                >
                  <el-option label="单次" :value="1"></el-option>
                  <el-option label="循环" :value="2"></el-option>
                  <el-option label="永久" :value="3"></el-option>
                </el-select>
              </el-form-item> -->
              <!-- 每天启用 -->
              <el-form-item label="定时模式">
                <el-select
                  v-model="form.days"
                  placeholder="请选择"
                  @change="ClearChange"
                >
                  <el-option label="某天播报" :value="0"></el-option>
                  <el-option label="限时播报" :value="1"></el-option>
                  <el-option label="每天播报" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <!-- 限时广播播日期 -->
              <el-form-item
                label="开始日期和时间"
                prop="time"
                v-if="form.days === 1"
              >
                <el-date-picker
                  value-format="yyyy-MM-dd"
                  v-model="form.time"
                  range-separator="至"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="最后开始结束日期"
                >
                </el-date-picker
                >&nbsp;&nbsp;&nbsp;&nbsp;
                <!-- <span>ps:循环播报时间不能大于5分钟</span> -->
              </el-form-item>

              <!-- 限时广播播放时间 -->
              <el-form-item label="时钟" prop="time" v-if="form.days === 1">
                <el-time-picker
                  value-format="THH:mm:ss"
                  v-model="form.clock"
                  arrow-control
                >
                </el-time-picker>
              </el-form-item>

              <!-- 广播播放时间段 -->
              <el-form-item label="日期和时间" v-if="form.days !== 1">
                <el-date-picker
                  value-format="timestamp"
                  v-model="form.time"
                  type="datetime"
                  placeholder="开始日期"
                >
                </el-date-picker>
              </el-form-item>
              <!-- 播报间隔 -->
              <el-form-item label="播报间隔">
                <el-input v-model="form.interval" style="width: 80px"></el-input
                >分钟
              </el-form-item>
              <!-- 播报次数-->
              <el-form-item
                label="播报次数"
                prop="broadcast_times"
                v-if="activeName === 'first'"
              >
                <el-input v-model="form.times" style="width: 80px"></el-input
                >次数
              </el-form-item>
              <!-- 接收方ID -->
              <el-form-item label="接收方" prop="call_id">
                <template>
                  <el-select
                    v-model="form.sip_obj"
                    placeholder="请选择"
                    @change="sipChange"
                    multiple
                    collapse-tags
                  >
                    <!-- <el-option label="关掉" value="8012"> </el-option>
                    <el-option label="强强强强" value="1001"> </el-option> -->
                    <el-option
                      v-for="item in callData"
                      :key="item.id"
                      :label="item.label"
                      :value="{ value: item.value, ip: item.ip_gateway }"
                    >
                    </el-option>
                  </el-select>
                  <span style="margin-left: 5px"
                    ><el-checkbox v-model="checked" @change="checkedFn"
                      >全选</el-checkbox
                    ></span
                  >
                </template>
              </el-form-item>
              <!-- <el-form-item label="接收方ID" prop="call_id" v-else>
                <el-input v-model="form.call_id"></el-input>
              </el-form-item> -->
              <!-- 播报内容类型 -->
              <!-- <el-form-item label="播报内容类型" prop="cont_type">
                <el-input
                  v-if="data.id"
                  disabled
                  v-model="form.cont_type"
                  placeholder="0是文字播报;  1是路径播报;"
                ></el-input>
                <el-input
                  v-else
                  v-model="form.cont_type"
                  placeholder="0是文字播报;  1是路径播报;"
                ></el-input>
              </el-form-item> -->
              <!-- 播报内容/播报文件路径 -->
              <el-form-item label="播报内容" prop="content">
                <el-input v-model="form.content"></el-input>
              </el-form-item>
              <!-- 播报内容/播报文件路径 -->
              <!-- <el-form-item label="语速倍数">
                <el-input v-model="form.speed"></el-input>
              </el-form-item> -->
              <!-- 播报内容/播报文件路径 -->
              <!-- <el-form-item label="音色">
                <el-input v-model="form.voice_type"></el-input>
              </el-form-item> -->
              <!-- 请求按钮 -->
              <div class="sipButton">
                <el-button type="primary" @click="getSip('form')"
                  >确定</el-button
                >
                <el-button icon="el-icon-refresh-left" @click="reset"
                  >重置</el-button
                >
              </div>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSipData,
  getTimingTable,
  sipDelete,
  sipGet,
  sipUpdate,
  sipStaus,
  ajaxInitiator,
  sipLoopSend,
  siptimingSend,
  getTimingSendTable,
  getTimingCycleTable,
} from "@/api/sip";

import { Message } from "element-ui";
import { getcheck } from "../encapsulation";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      // sip数据表格
      sipTable: [],
      sipForm: {},
      CycleAndSenddialogVisible: false,
      // 加载
      loading: false,
      //频道全选
      checked: false,
      //获取sip发起地数据
      callData: [],
      // 分页
      paging: {
        pag: 1,
        limit: 10,
        total: 100,
      },
      form: {
        sip_ip: "", //sip地址
        sip_port: "", //sip端口
        user_id: "", //发起id
        password: "", //密码
        call_id: "", //接收id
        content: "", //内容
        start_time_date: "", //播报起始时间
        end_time_date: "", //播报结束时间
        time: "", //时间需要转换参数
        days: "", //是否每天播放
        interval: "", //间隔时间
        times: "", //播放次数
        clock: "", //时钟
        sip_obj: {},
      },
      activeName: "first",
      ajaxInitiatorName: [],
      // 定时参数必填规则
      Rules: {
        time: [
          // { required: true, message: "日期时间不能为空", trigger: "blur" },
        ],
        // broadcast_mode: [
        //   { required: true, message: "请选择播报模式", trigger: "blur" },
        // ],
        // broadcast_interval: [
        //   { required: true, message: "请选择播报间隔", trigger: "blur" },
        // ],
        sip_ip: [
          { required: true, message: "sip服务器不能为空", trigger: "blur" },
        ],
        sip_port: [
          { required: true, message: "Sip服务器端口不能为空", trigger: "blur" },
        ],
        user_id: [
          { required: true, message: "发起方ID不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "发起方密码不能为空", trigger: "blur" },
        ],
        call_id: [
          { required: true, message: "接收方ID不能为空", trigger: "blur" },
        ],
        cont_type: [
          { required: true, message: "播报内容类型不能为空", trigger: "blur" },
        ],
        content: [
          {
            required: true,
            message: "播报内容/播报文件路径不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.sipInit(1, "first");
    // this.sipSend();
    // this.sipOpen();
  },
  methods: {
    async sipInit(page, activeName) {
      let name = JSON.parse(localStorage.getItem("HSKJ-username"));
      // this.sipTable = data;
      //循环播报
      if (activeName === "first") {
        const ajaxInitiatorData = await ajaxInitiator({ userChanne: name });
        this.ajaxInitiatorName = ajaxInitiatorData.data.meta.data;
        //获取发起地ids 提供给表格使用
        let call_ids = ajaxInitiatorData.data.meta.data.map((item) => {
          return item.Initiator_id;
        });
        //表格数据
        const res = await getTimingSendTable({ pag: page || 1, call_ids });
        this.sipTable = res.data.data.rows;
        // this.sipTable = data;
        this.paging.total = res.data.data.total;
      }
      if (activeName === "second") {
        const res = await getTimingCycleTable({ pag: page || 1 });
        const ajaxInitiatorData = await ajaxInitiator({ userChanne: name });
        this.sipTable = res.data.data.rows;
        // this.sipTable = data;
        this.paging.total = res.data.data.total;
        this.ajaxInitiatorName = ajaxInitiatorData.data.meta.data;
      }

      //循环匹配发起地
      this.sipTable.forEach((item) => {
        let calliIdName = [];
        this.ajaxInitiatorName.forEach((elemnt) => {
          if (Number(item.call_id) === elemnt.Initiator_id) {
            item.call_name = elemnt.Initiator_name;
          }

          let calliIdList = item.call_id.split("@");

          if (calliIdList.length >= 2) {
            calliIdList.forEach((val) => {
              if (Number(val) === elemnt.Initiator_id) {
                calliIdName.push(elemnt.Initiator_name);
              }
            });
            item.call_name = calliIdName.join("@");
          }
        });
      });
    },
    async sipSend() {
      this.CycleAndSenddialogVisible = true;
      let res = await sipGet();
      this.sipForm = res.data.data[0];
      this.form.sip_ip = this.sipForm.sip_sever;
      this.form.sip_port = this.sipForm.port;
      this.form.user_id = this.sipForm.user_id;
      this.form.password = this.sipForm.password;
    },
    async getSip() {
      if (this.activeName === "first") {
        this.form.interval = String(this.form.interval * 60);
        // 乘1000换算秒数
        if (this.form.days !== 1) {
          this.form.start_time_date = String(this.form.time / 1000);
        } else {
          let newStartTime = new Date(
            this.form.time[0] + this.form.clock
          ).getTime();
          let newEndtTime = new Date(
            this.form.time[1] + this.form.clock
          ).getTime();

          this.form.start_time_date = String(newStartTime / 1000);
          this.form.end_time_date = String(newEndtTime / 1000);
        }

        if (this.form.sip_obj.length >= 2) {
          this.form.call_id = this.form.call_id.join("@");
          this.form.sip_ip = this.form.sip_ip.join("@");
        } else {
          this.form.call_id = this.form.call_id[0];
          this.form.sip_ip = this.form.sip_ip[0];
        }

        if (this.form.days !== 1) {
          this.form.end_time_date = 0;
        }

        if (this.form.interval < 5) {
          Message.warning("时间大于5秒");
          return;
        }
        //判断
        if (this.form.days === 1) {
          let res = await siptimingSend({
            sip_ip: this.form.sip_ip,
            sip_port: this.form.sip_port,
            user_id: this.form.user_id,
            call_id: this.form.call_id,
            content: this.form.content,
            start_time_date: this.form.start_time_date,
            interval: this.form.interval,
            times: this.form.times,
            days: String(this.form.days),
          });

          if (res.status === 200) {
            this.form = {
              sip_ip: "", //sip地址
              sip_port: "", //sip端口
              user_id: "", //发起id
              password: "", //密码
              call_id: "", //接收id
              content: "", //内容
              start_time_date: "", //播报起始时间
              end_time_date: "", //播报结束时间
              time: "", //时间需要转换参数
              days: "", //是否每天播放
              interval: "", //间隔时间
              times: "", //播放次数
              clock: "", //时钟
            };
            this.CycleAndSenddialogVisible = false;
            Message.success(res.data.status_msg);
            this.sipInit(1, this.activeName);
          }
        } else {
          let res = await siptimingSend({
            sip_ip: this.form.sip_ip,
            sip_port: this.form.sip_port,
            user_id: this.form.user_id,
            call_id: this.form.call_id,
            content: this.form.content,
            start_time_date: this.form.start_time_date,
            interval: this.form.interval,
            times: this.form.times,
            days: String(this.form.days),
            end_time_date: this.form.end_time_date,
          });

          if (res.status === 200) {
            this.form = {
              sip_ip: "", //sip地址
              sip_port: "", //sip端口
              user_id: "", //发起id
              password: "", //密码
              call_id: "", //接收id
              content: "", //内容
              start_time_date: "", //播报起始时间
              end_time_date: "", //播报结束时间
              time: "", //时间需要转换参数
              days: "", //是否每天播放
              interval: "", //间隔时间
              times: "", //播放次数
              clock: "", //时钟
            };
            this.CycleAndSenddialogVisible = false;
            Message.success(res.data.status_msg);
            this.sipInit(1, this.activeName);
          }
        }
      }

      if (this.activeName === "second") {
        // 乘1000换算秒数
        this.form.start_time = String(this.form.time[0] / 1000);
        this.form.end_time = String(this.form.time[1] / 1000);

        if (this.form.call_id.length >= 2) {
          this.form.call_id = this.form.call_id.join("@");
        } else {
          this.form.call_id = this.form.call_id[0];
        }

        if (this.form.days === 1) {
          this.form.end_time_date = String(this.form.end_time_date / 1000);
        }
        this.form.times = "-1";

        console.log(568, this.form.time);

        let res = await siptimingSend(this.form);

        console.log(572, res);
        if (res.status === 200) {
          this.form = {
            sip_ip: "", //sip地址
            sip_port: "", //sip端口
            user_id: "", //发起id
            password: "", //密码
            call_id: "", //接收id
            content: "", //内容
            start_time: "", //播报起始时间
            end_time: "", //播报结束时间
            end_time_date: "", //最后一天日期
            time: "", //时间需要转换参数
            days: "", //是否每天播放
            interval: "", //间隔时间
            times: "", //播放次数
          };
          this.CycleAndSenddialogVisible = false;
          Message.success(res.data.status_msg);
          this.sipInit(1, this.activeName);
        }
      }
    },
    // 导出excel
    exportToExcel() {
      // 直接使用XLSX的内置导出方法
      const ws = XLSX.utils.json_to_sheet(
        this.sipTable.map((item) => ({
          接收地: item.call_name,
          播报内容: item.content,
          开始时间: this.$moment(item.start_time * 1000).format(
            "YYYY-MM-DD/HH:mm"
          ),
          广播模式:
            item.days === 0
              ? "某天播放"
              : item.days === 1
              ? "限时播放"
              : item.days === 2
              ? "每天播放"
              : "",
          播报次数: item.times + "次",
          播报间隔: item.interval / 60 + "分钟",
          广播状态:
            item.status === 0 ? "未播放" : item.status === 1 ? "已播放" : "",
        }))
      );

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "定时表格");

      // 直接导出文件（不需要file-saver）
      XLSX.writeFile(wb, "定时表格.xlsx");
    },
    async sipOpen() {
      let name = JSON.parse(localStorage.getItem("HSKJ-username"));
      const res = await ajaxInitiator({ userChanne: name });
      this.callData = res.data.meta.data;
      // // 处理成element ui 使用的格式
      this.callData.forEach((item) => {
        item.label = item.Initiator_name;
        item.value = String(item.Initiator_id);
      });
    },
    // 分页
    page_change(data) {
      this.sipInit(data, "first");
    },
    //定时模式变化清空数据
    ClearChange() {
      this.form.start_time_date = "";
      this.form.end_time_date = "";
      this.form.time = "";
      this.form.clock = "";
    },
    async del(data) {
      await sipDelete({ id: String(data.id), activeName: this.activeName });
      Message.success("删除成功");
      this.sipInit(1, this.activeName);
    },
    // 全选
    checkedFn() {
      this.form.sip_obj = [];
      this.form.sip_ip = [];
      this.form.call_id = [];
      if (this.checked === true) {
        this.form.sip_obj = this.callData.map((option) => {
          // String(option.Initiator_id)
          return { value: String(option.Initiator_id), ip: option.ip_gateway };
        });
        this.form.sip_ip = this.form.sip_obj.map((item) => item.ip);
        this.form.call_id = this.form.sip_obj.map((item) => String(item.value));
        // console.log(656, this.form.sip_obj);
      } else {
        this.form.sip_obj = [];
        this.form.sip_ip = [];
        this.form.call_id = [];
      }
    },
    close() {
      this.CycleAndSenddialogVisible = false;
    },
    // 选择值
    sipChange(data) {
      //多选
      // this.form.call_id = data

      // 收集选择之对象
      this.form.sip_obj = data;
      //提取数据
      this.form.call_id = this.form.sip_obj.map((item) => {
        return item.value;
      });
      this.form.sip_ip = this.form.sip_obj.map((item) => {
        return item.ip;
      });
    },
    reset() {
      this.form = {
        sip_ip: "",
        sip_port: "",
        user_id: "",
        password: "",
        call_id: "",
        content: "",
        start_time: "",
        end_time: "",
        time: "",
        everyday: "",
        broadcast_mode: "",
      };
    },
    handleClick(tab, event) {
      this.sipInit(1, this.activeName);
    },
  },
};
</script>

<style>
.sipButton {
  display: flex;
  justify-content: center;
}
.title {
  text-align: center;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
